package com.chengww.grab_rp.activities

import android.app.Activity
import android.content.Intent
import android.view.View
import androidx.lifecycle.lifecycleScope
import com.chengww.grab_rp.R
import com.chengww.grab_rp.base.BaseActivity
import com.chengww.grab_rp.database.user.UserDao
import com.chengww.grab_rp.databinding.ActivityLoginBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LoginActivity : BaseActivity<LoginViewModel, ActivityLoginBinding>() {
    override fun layoutId() = R.layout.activity_login

    private val userDao: UserDao by lazy { UserDao.getInstance(this) }

    override fun provideVM() = LoginViewModel(userDao)

    override fun initView() {
        lifecycleScope.launch {
            // Check if user is logged in
            val userLoggedIn = withContext(Dispatchers.IO) {
                userDao.isUerLoggedIn()
            }
            if (userLoggedIn) {
                toHome()
            }
        }

        supportActionBar?.setDisplayShowHomeEnabled(false)
        supportActionBar?.setTitle(R.string.btn_login)
        vm.loginResponse.observe(this) {
            toHome()
        }

    }

    override fun onClick(view: View) {
        when(view.id) {
            R.id.btn_login -> {
                val pluginId = vm.pluginId.value
                if (pluginId.isNullOrEmpty()) {
                    toast(R.string.hint_plugin_id)
                    return
                }
                val md5Key = vm.md5Key.value
                if (md5Key.isNullOrEmpty()) {
                    toast(R.string.hint_md5_key)
                    return
                }
                vm.login(pluginId, md5Key)
            }
            R.id.btn_help -> HelpActivity.newIntent(this)
        }
    }

    private fun toHome() {
        HomeActivity.newIntent(this)
        finish()
    }

    companion object {

        fun restartApp(activity: Activity) {
            val intent = Intent(activity, LoginActivity::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            activity.startActivity(intent)
        }
    }

}